﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using HosPlat.Data;
using FastReflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Data;
using System.Text;

namespace HosPlat.API.Base
{
    public class BaseManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var methodInfo = typeof(BaseManage).GetMethod(msg.action.ToUpper().Split('_')[1]);
            BaseManage model = new BaseManage();
            methodInfo.Invoke(model, new object[] { context, msg, page, authuser, P1, P2 });
        }

        #region 登录
        public void LOGIN(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            if (P1 == "" || P2 == "")
            {
                msg.error = "请输入用户名和密码";
                return;
            }

            var usr = new HT_Auth_UserB().GetEntity(p => p.UserName == P1 && p.Password == P2);
            if (usr == null)
            {
                msg.error = "用户名或者密码不正确";
            }
            else
            {
                if (string.IsNullOrEmpty(usr.Code))
                {
                    usr.Code = Guid.NewGuid().ToString();
                    usr.CodeTime = DateTime.Now;

                    new HT_Auth_UserB().Update(usr);
                }
                msg.result = usr.Code;
            }

        }
        public void GETUSERINFO(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            msg.result = new
            {
                ID = authuser.ID,
                UserName = authuser.UserName,
                UserXM = authuser.UserXM,
                TelePhone = authuser.TelePhone
            };
        }
        public void CHNPWD(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            if (authuser == null || authuser.ID == 0)
            {
                msg.error = "请先登录";
                return;
            }
            if (P1 == "")
            {
                msg.error = "请输入原始密码";
                return;
            }
            if (P2 == "")
            {
                msg.error = "请输入新密码";
                return;
            }
            var usr = new HT_Auth_UserB().GetEntity(p => p.ID == authuser.ID && p.Password == P1);
            if (usr == null)
            {
                msg.error = "原密码错误";
                return;
            }

            new HT_Auth_UserB().ExsSql(string.Format("update HT_Auth_User set Password='{0}' where ID='{1}' ", P2, authuser.ID));


        }
        #endregion

        #region 获取菜单
        public void GETMENU(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            if (authuser.Role.HasValue)
            {
                int role = authuser.Role.Value;
                var authR = new HT_Auth_RoleB().GetEntity(p => p.ID == role);
                if (authR != null)
                {
                    string SQL1 = "select * from HT_Auth_Menu where ISVAL=1 and TopID=0 ";
                    if (authR.IsAdmin != "1")
                    {
                        SQL1 += " and ID in(" + authR.RoleAuth + ") ";
                    }
                    SQL1 += " order by sort ";
                    DataTable dt = new HT_Auth_MenuB().GetDTByCommand(SQL1);
                    dt.Columns.Add("SubItem", typeof(DataTable));
                    foreach (DataRow dr in dt.Rows)
                    {
                        string SQL2 = string.Format("select * from HT_Auth_Menu where ISVAL=1 and TopID={0} ", dr["ID"].ToString());
                        if (authR.IsAdmin != "1")
                        {
                            SQL2 += " and ID in(" + authR.RoleAuth + ") ";
                        }
                        SQL2 += " order by sort ";

                        var dt2 = new HT_Auth_MenuB().GetDTByCommand(SQL2);
                        dr["SubItem"] = dt2;
                    }
                    msg.result = dt;

                }
            }

        }
        public void GETAUTHMENU(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User UserInfo, string P1, string P2)
        {
            int roleid = 0;
            if (P1 != "")
            {
                roleid = Int32.Parse(P1);
            }
            string roles = "";
            var authR = new HT_Auth_RoleB().GetEntity(p => p.ID == roleid);
            if (authR != null && !string.IsNullOrEmpty(authR.RoleAuth))
            {
                roles = "," + authR.RoleAuth + ",";
            }

            string SQL1 = "select *,CHARINDEX(','+cast(ID as varchar)+',','" + roles + "') as issel from HT_Auth_Menu where ISVAL=1 and TopID=0 ";
            SQL1 += " order by sort ";
            DataTable dt = new HT_Auth_MenuB().GetDTByCommand(SQL1);
            dt.Columns.Add("SubItem", typeof(DataTable));
            foreach (DataRow dr in dt.Rows)
            {
                string SQL2 = string.Format("select * ,CHARINDEX(','+cast(ID as varchar)+',','" + roles + "') as issel from HT_Auth_Menu where ISVAL=1 and TopID={0} ", dr["ID"].ToString());
                SQL2 += " order by sort ";

                var dt2 = new HT_Auth_MenuB().GetDTByCommand(SQL2);
                dr["SubItem"] = dt2;
            }
            msg.result = dt;

        }
        #endregion

        #region 用户权限管理
        public void GETUSER(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string strWhere = " 1=1 ";
            string SearchKey = context.Request["SearchKey"];
            if (!string.IsNullOrEmpty(SearchKey))
            {
                strWhere += string.Format(" and (u.UserName like '%{0}%' or u.UserXM like '%{1}%' or u.TelePhone like '%{2}%' ) ", SearchKey, SearchKey, SearchKey);
            }

            int total = 0;
            var dt = new HT_Auth_UserB().GetDataPager("HT_Auth_User u left join HT_Auth_Role r on u.Role=r.ID ", "u.*,r.RoleName", page.pagecount, page.pageindex, " u.CRTime desc", strWhere, ref total);

            msg.result = dt;
            msg.total = total;
        }
        public void GETUSERMODEL(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            msg.result = new HT_Auth_UserB().GetEntity(p => p.ID == ID);

        }

        public void ADDUSER(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var tt = JsonConvert.DeserializeObject<HT_Auth_User>(P1);
            if (string.IsNullOrEmpty(tt.UserName) || string.IsNullOrEmpty(tt.Password))
            {
                msg.error = "请输入用户名和密码";
                return;
            }
            if (tt.ID == 0)
            {
                //判断用户名是否存在
                var ishas = new HT_Auth_UserB().GetEntity(p => p.UserName == tt.UserName);
                if (ishas != null)
                {
                    msg.error = "用户名已存在";
                    return;
                }
                tt.CRTime = DateTime.Now;
                new HT_Auth_UserB().Insert(tt);
            }
            else
            {
                new HT_Auth_UserB().Update(tt);
            }

        }
        public void DELUSER(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            new HT_Auth_UserB().Delete(p => p.ID == ID);

        }

        public void GETROLEMODEL(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            msg.result = new HT_Auth_RoleB().GetEntity(p => p.ID == ID);

        }

        public void GETROLE(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string strWhere = " 1=1 ";
            string SearchKey = context.Request["SearchKey"];
            if (!string.IsNullOrEmpty(SearchKey))
            {
                strWhere += string.Format(" and (RoleName like '%{0}%' or RoleDesp like '%{1}%') ", SearchKey, SearchKey);
            }
            int total = 0;
            var dt = new HT_Auth_RoleB().GetDataPager("HT_Auth_Role", "*", page.pagecount, page.pageindex, " CRTime desc", strWhere, ref total);

            msg.result = dt;
            msg.total = total;
        }

        public void ADDROLE(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var tt = JsonConvert.DeserializeObject<HT_Auth_Role>(P1);
            if (tt.ID == 0)
            {
                tt.CRTime = DateTime.Now;
                new HT_Auth_RoleB().Insert(tt);
            }
            else
            {
                new HT_Auth_RoleB().Update(tt);
            }

        }
        public void DELROLE(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            new HT_Auth_RoleB().Delete(p => p.ID == ID);

        }
        #endregion

        #region 楼号管理
        public void ADDLOU(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int QTY = Int32.Parse(P2);
            var lou = new HT_LouB().GetEntity(p => p.LouNo == P1);
            if (lou == null)
            {
                //添加大楼

                var ll = new HT_Lou()
                {
                    LouNo = P1,
                    LouNum = QTY,
                    CRTime = DateTime.Now,
                    CRUser = authuser.ID
                };
                new HT_LouB().Insert(ll);

                //添加楼层
                for (int i = 1; i <= QTY; i++)
                {
                    var ly = new HT_LayerB().GetEntity(p => p.LYNO == i && p.LouID == ll.ID);
                    if (ly == null)
                    {
                        new HT_LayerB().Insert(new HT_Layer()
                        {
                            LYNO = i,
                            CRTime = DateTime.Now,
                            CRUser = authuser.ID,
                            IsSync = 0,
                            LouID = ll.ID
                        });
                    }
                }

            }
            else
            {
                msg.error = "该楼已存在";
            }
        }
        public void GETLOU(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            msg.result = new HT_LouB().GetDTByCommand("select * from HT_Lou");
        }
        #endregion

        #region 获取楼层数据，管理楼层，楼>>楼层>>通道

        public void GETLAYC(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string strWhere = " 1=1 ";
            //string SearchKey = context.Request["SearchKey"];
            //if (!string.IsNullOrEmpty(SearchKey))
            //{
            //    strWhere += string.Format(" and (RoleName like '%{0}%' or RoleDesp like '%{1}%') ", SearchKey, SearchKey);
            //}
            int total = 0;
            page.pagecount = 999;
            var dt = new HT_LayerB().GetDataPager("HT_Layer", "*", page.pagecount, page.pageindex, " LYNO desc", strWhere, ref total);

            msg.result = dt;
            msg.total = total;
        }

        public void GETLAYCTREE(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            //楼>>楼层>>通道

            var dt0 = new HT_LayerB().GetDTByCommand("select ID,LouNo as name,1 as lvl from HT_Lou ");
            dt0.Columns.Add("children", typeof(DataTable));
            foreach (DataRow dr0 in dt0.Rows)
            {
                string SQL1 = "select ID,cast(LYNO as varchar)+'楼 '+isnull(SetupAD,'') as name,2 as lvl from HT_Layer where LouID='" + dr0["ID"].ToString() + "' order by LYNO asc";
                var dt = new HT_LayerB().GetDTByCommand(SQL1);
                if (P2 == "1") //包括通道
                {
                    dt.Columns.Add("children", typeof(DataTable));
                    foreach (DataRow dr in dt.Rows)
                    {
                        string SQL2 = "select ID,PathName as name, 3 as lvl from HT_Path where LYID='" + dr["ID"].ToString() + "' order by ID asc ";
                        var dt2 = new HT_PathB().GetDTByCommand(SQL2);
                        if (dt2.Rows.Count > 0)
                        {
                            dr["children"] = dt2;
                        }

                    }
                }
                dr0["children"] = dt;
            }
            //string strWhere = " 1=1 ";
            ////string SearchKey = context.Request["SearchKey"];
            ////if (!string.IsNullOrEmpty(SearchKey))
            ////{
            ////    strWhere += string.Format(" and (RoleName like '%{0}%' or RoleDesp like '%{1}%') ", SearchKey, SearchKey);
            ////}
            //int total = 0;
            //page.pagecount = 999;
            //var dt = new HT_LayerB().GetDataPager("HT_Layer", "*", page.pagecount, page.pageindex, " LYNO desc", strWhere, ref total);

            msg.result = dt0;
            //msg.total = total;
        }



        /// <summary>
        /// 获取楼层设备信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void GETLAYCMODEL(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            msg.result = new HT_LayerB().GetEntity(p => p.ID == ID);
        }

        /// <summary>
        /// 添加楼层
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1">最大楼层号码</param>
        /// <param name="P2"></param>
        public void ADDLAYC(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            int LYNO = Int32.Parse(P2);
            string remark = context.Request["Remark"];

            var lou = new HT_LouB().GetEntity(p => p.ID == ID);
            if (lou != null)
            {
                new HT_LayerB().Insert(new HT_Layer()
                {
                    LYNO = LYNO,
                    CRTime = DateTime.Now,
                    CRUser = authuser.ID,
                    IsSync = 0,
                    LouID = ID,
                    SetupAD = remark,
                    Status = "0"
                });
            }
            else
            {
                msg.error = "楼号不存在";
            }

        }
        public void DELLAYC(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            if (P2 == "1") //删除楼
            {
                var list = new HT_LayerB().GetEntities(p => p.LouID == ID);
                if (list.Count() > 0)
                {
                    msg.error = "有设备不能删除";
                }
                else
                {
                    new HT_LouB().Delete(p => p.ID == ID);
                }
            }
            else if (P2 == "2") // 删除楼层
            {
                new HT_LayerB().Delete(p => p.ID == ID);
                new HT_PathB().Delete(p => p.LYID == ID);
                new HT_PathDataB().Delete(p => p.LYID == ID);
            }


        }
        /// <summary>
        /// 修改楼层设备信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void UPDATELAYC(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var tt = JsonConvert.DeserializeObject<HT_Layer>(P1);
            if (tt.ID != 0)
            {
                var hl = new HT_LayerB().GetEntity(p => p.ID == tt.ID);
                if (hl != null)
                {

                    if (hl.IP != tt.IP)
                    {
                        hl.IP = tt.IP;
                        hl.IsSync = 0;//修改ip需要获取通道信息
                    }
                    //端口
                    if (hl.Port != tt.Port)
                    {
                        hl.Port = tt.Port;
                        hl.IsSync = 0;//修改ip需要获取通道信息
                    }

                    //设备地址
                    if (hl.EquAD != tt.EquAD)
                    {
                        hl.EquAD = tt.EquAD;
                        hl.IsSync = 0; //修改ip需要获取通道信息
                    }

                    //修改设备名称
                    //if (hl.EquName != tt.EquName)
                    //{
                    hl.EquName = tt.EquName;
                    //hl.IsSync = 0; //修改设备名称需要同步到硬件设备

                    ToolUtil.SetEquName(tt.IP, tt.Port, tt.EquAD, tt.EquName);
                    //}
                    //安装位置
                    //if (hl.SetupAD != tt.SetupAD)
                    //{
                    hl.SetupAD = tt.SetupAD;

                    ToolUtil.SetSetupADD(tt.IP, tt.Port, tt.EquAD, tt.SetupAD);
                    //}

                    new HT_LayerB().Update(hl);
                }
            }
        }
        public void FRESHLAYER(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            new HT_LayerB().ExsSql("update HT_Layer set IsSync=0 where ID=" + P1);
        }
        public void FRESHLAYERALL(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            new HT_LayerB().ExsSql("UPDATE HT_Layer set IsSync=0 where IsSync=1 and convert(char(10), IsSyncTime,120)!=convert(char(10),getdate(),120) and IP!='' and Port!='' and EquAD!='' ");
        }
        #endregion

        #region 设备，通道管理

        /// <summary>
        /// 获取设备通道信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void GETPATHMODEL(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            int ID = Int32.Parse(P1);
            msg.result = new HT_PathB().GetEntity(p => p.ID == ID);
        }
        public void GETPATHLIST(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string strWhere = " 1=1 ";
            if (P1 != "")
            {
                strWhere += " and LYID='" + P1 + "' ";

                int total = 0;
                page.pagecount = 999;
                var dt = new HT_PathB().GetDataPager("HT_Path", "*", page.pagecount, page.pageindex, " ID asc", strWhere, ref total);

                msg.result = dt;
                msg.total = total;
            }


        }

        public void GETPATHDATALIST(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string errflag = context.Request["errflag"] ?? "";
            string old = context.Request["old"] ?? "";
            string strWhere = " 1=1 ";
            if (P1 != "")
            {
                strWhere += " and p.LYID='" + P1 + "'";
            }
            if (P2 != "")
            {
                strWhere += " and p.ID='" + P2 + "'";
            }
            if (errflag == "1")
            {
                strWhere += " and d.PathStatus!='正常'";
            }

            int total = 0;

            string SQLT = "HT_Path p join HT_PathData d on p.ID=d.PID";
            if(old!="")
            {
                SQLT = "HT_Path p join HT_PathData_bak d on p.ID=d.PID";
            }
            var dt = new HT_PathDataB().GetDataPager(SQLT, "d.*,p.PathName", page.pagecount, page.pageindex, " d.CRTime desc", strWhere, ref total);

            msg.result = dt;
            msg.total = total;
        }

        /// <summary>
        /// 修改通道
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void UPDATEPATH(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var tt = JsonConvert.DeserializeObject<HT_Path>(P1);
            if (tt.ID != 0)
            {
                new HT_PathB().ExsSql("update HT_Path set PathName='" + tt.PathName + "',IsSync=0 where ID=" + tt.ID);

                var ly = new HT_LayerB().GetEntity(p => p.ID == tt.LYID);
                //同步更新到接口

                //ToolUtil.SetPathName(ly.IP, ly.Port, ly.SetupAD, tt.PathName, tt.PathNo.Value);

            }
        }


        /// <summary>
        /// 修改通道名称
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        //public void UPDATEPATHNAME(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        //{

        //    int ID = Int32.Parse(P1);
        //    new HT_PathB().ExsSql("update HT_Path set PathName='" + P2 + "',IsSync=0 where ID=" + ID);

        //    //同步更新到接口
        //    //new HT_LayerB().GetEntity(p=>p.LYNO)
        //    //ToolUtil.SetPathName("01","01", "设备你好");
        //    //ToolUtil.SetEquTime("01");

        //}
        #endregion

        #region 自动获取通道数据
        public void AUTO(int runCount)
        {
            //string d1 = "0102";
            //string version = d1.Substring(0, 2) + "." + d1.Substring(2, 2);
            //1.判断设备是否同步
            //var list1 = new HT_LayerB().GetEntities(p => p.IsSync == 0);
            //foreach(var v in list1)
            //{
            //    ToolUtil.SetEquTime(v.EquAD, v.Port, v.EquName);
            //}
            try
            {
                //ToolUtil.SetSetupADD("192.168.1.125", "5000", "01", "实验楼1楼");
                //ToolUtil.SetEquName("192.168.1.125", "5000", "01", "郑州市第一人民医院");
                //ToolUtil.SetEquTime("192.168.1.125", "5000", "01");

                //检测通道数是否正确：12点检测
                //var listfirst = new HT_LayerB().GetEntities(p => p.IP != "" && p.IP != null && p.Port != "" && p.Port != null && p.EquAD != "" && p.EquAD != null);


                int dIndex = 0;
                #region 2.获取设备信息
                DateTime now = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
                var list2 = new HT_LayerB().GetEntities(p => p.IP != "" && p.IP != null && p.Port != "" && p.Port != null && p.EquAD != "" && p.EquAD != null && (p.IsSync == 0 || (p.IsSyncTime.Value < now)));
                foreach (var v in list2)
                {
                    if (!string.IsNullOrEmpty(v.EquAD) && !string.IsNullOrEmpty(v.Port) && !string.IsNullOrEmpty(v.IP))
                    {
                        //1.更新设备时间
                        ToolUtil.SetEquTime(v.IP, v.Port, v.EquAD);

                        dIndex = 0;
                        string layinfo = ToolUtil.GetEquInfo(v.IP, v.Port, v.EquAD);
                        //layinfo= "02 03 62 01 01 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 11 0B 0B 16 00 2F 00 02 00 01 00 00 00 05 00 05 C4 FE B2 A8 CA D0 B5 DA B6 FE C8CB C3 F1 D2 BD D4 BA 20 00 00 00 00 00 00 00 00 00 00 00 00 00 B6 F9 BF C6 B2 A1 C7 F8 32 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 C7 D5";

                        layinfo = layinfo.Replace(" ", "");
                        if (layinfo == "")
                        {
                            //设备异常
                            new HT_LayerB().ExsSql("update HT_Layer set Status='0' where ID=" + v.ID);
                            continue;
                        }
                        new HT_LayerB().ExsSql("update HT_Layer set Status='1' where ID=" + v.ID);
                        //分析设备信息
                        int len = CRC.HexToInt(layinfo.Substring(4, 2)) * 2; //一个字节两位
                        string data = layinfo.Substring(6, len);

                        string d1 = data.Substring(dIndex, 4);//版本
                        v.EquVersion = "V" + CRC.HexToInt(d1.Substring(0, 2)).ToString() + "." + d1.Substring(2, 2);
                        dIndex += 4;

                        string d2 = data.Substring(dIndex, 4);  //设备型号
                        v.EquModel = d2;
                        dIndex += 4;

                        string d3 = data.Substring(dIndex, 4);  //最大通道数
                        v.MaxPath = CRC.HexToInt(d3.Substring(2, 2));
                        dIndex += 4;

                        dIndex += (4 * 6);

                        string d4 = data.Substring(dIndex, 4);  //系统时间（年月）
                        string year = (CRC.HexToInt(d4.Substring(0, 2)) + 2000).ToString();
                        string month = CRC.HexToInt(d4.Substring(2, 2)).ToString();
                        dIndex += 4;

                        string d5 = data.Substring(dIndex, 4);  //系统时间（日 时）
                        string day = (CRC.HexToInt(d5.Substring(0, 2))).ToString();
                        string hour = CRC.HexToInt(d5.Substring(2, 2)).ToString();
                        dIndex += 4;

                        string d6 = data.Substring(dIndex, 4);  //系统时间（分 秒）
                        string minute = (CRC.HexToInt(d6.Substring(0, 2))).ToString();
                        string second = CRC.HexToInt(d6.Substring(2, 2)).ToString();
                        dIndex += 4;

                        //string d7 = data.Substring(dIndex, 4);  //设备地址
                        //v.EquAD = d7;
                        dIndex += 4;


                        string d8 = data.Substring(dIndex, 4);  //设备波特率
                        if (d8 == "0000")
                        {
                            v.EquBit = "2400";
                        }
                        else if (d8 == "0001")
                        {
                            v.EquBit = "4800";
                        }
                        else if (d8 == "0002")
                        {
                            v.EquBit = "9600";
                        }
                        else
                        {
                            v.EquBit = "4800";
                        }

                        dIndex += 4;

                        string d9 = data.Substring(dIndex, 4);  //节电模式
                        if (d9 == "0001")
                        {
                            v.EquPower = "开启";
                        }
                        else
                        {
                            v.EquPower = "关闭";
                        }
                        dIndex += 4;

                        string d10 = data.Substring(dIndex, 4);  //告警延迟
                        v.EquWaring = CRC.HexToInt(d10).ToString();
                        dIndex += 4;

                        string d11 = data.Substring(dIndex, 4);  //故障延迟
                        v.EquError = CRC.HexToInt(d11).ToString();
                        dIndex += 4;

                        //设备名称
                        string d12 = data.Substring(dIndex, 4 * 16);
                        d12 = d12.Replace("0000", "");
                        if (d12 != "")
                        {
                            v.EquName = CRC.GetChsFromHex(d12).TrimEnd().TrimEnd('\0').TrimEnd(' ');
                        }
                        dIndex += (4 * 16);

                        //设备安装位置
                        string d13 = data.Substring(dIndex, 4 * 16);
                        d13 = d13.Replace("0000", "");
                        if (d13 != "")
                        {
                            v.SetupAD = CRC.GetChsFromHex(d13).TrimEnd().TrimEnd('\0').TrimEnd(' ');
                        }

                        v.IsSync = 1;
                        v.IsSyncTime = DateTime.Now;
                        new HT_LayerB().Update(v);

                        string pnoList = "";
                        #region 通道属性分别来读取
                        for (int i = 0; i < v.MaxPath.Value; i++)
                        {
                            int pathNo = i + 1;
                            dIndex = 0;
                            //HT_Path hp = new HT_Path();
                            //hp.LYID = v.ID;

                            string seqinfo = ToolUtil.GetPathInfo(v.IP, v.Port, v.EquAD, i);
                            //seqinfo = "020308000000B0F9FF35FFD7 ";
                            seqinfo = seqinfo.Replace(" ", "");
                            if (seqinfo == "")
                            {
                                continue;
                            }
                            int len1 = CRC.HexToInt(seqinfo.Substring(4, 2)) * 2; //一个字节两位
                            string data1 = seqinfo.Substring(6, len1);


                            string t2 = data1.Substring(dIndex, 4);  //通道编号
                            int pNO = CRC.HexToInt(t2);
                            dIndex += 4;

                            // hp.PathNo = pNO

                            bool iu = false;
                            var hp = new HT_PathB().GetEntity(p => p.PathNo == pNO && p.LYID == v.ID);
                            if (hp == null)
                            {
                                iu = true;
                                hp = new HT_Path();
                                hp.PathNo = pNO;
                                hp.LYID = v.ID;
                            }

                            string t3 = data1.Substring(dIndex, 4);  //通道类型
                            hp.PathType = GetPathType(CRC.HexToInt(t3));
                            dIndex += 4;

                            string t3_ = data1.Substring(dIndex, 4);  //通道名称
                            //hp.PathType = GetPathType(CRC.HexToInt(t3));
                            dIndex += 4;

                            hp.PathName = GetPathTypeName(CRC.HexToInt(t3_));

                            string t4 = data1.Substring(dIndex, 4);  //单位
                            string t4_1 = GetPathUnit(CRC.HexToInt(t4.Substring(0, 2))); //单位

                            int t4_2 = CRC.HexToInt(t4.Substring(2, 2));   //小数位

                            hp.PathUnit = t4_1;
                            hp.PathDecimal = t4_2.ToString();
                            dIndex += 4;

                            string t5 = data1.Substring(dIndex, 4);  //量程
                            if (t4_2 == 0)
                            {
                                hp.PathValue = CRC.HexToInt(t5).ToString();
                            }
                            else
                            {
                                double iDecimal = Math.Pow(10, -t4_2);
                                hp.PathValue = ((decimal)(CRC.HexToInt(t5) * iDecimal)).ToString("F" + t4_2);
                            }

                            dIndex += 4;

                            string t6 = data1.Substring(dIndex, 4);  //偏移量 
                            int t6_i = CRC.HexToInt(t6);
                            int PathDiff = 0;
                            if (t6_i < 32768)
                            {
                                PathDiff = t6_i;
                            }
                            else
                            {
                                PathDiff = -(65536 - t6_i);
                            }
                            if (t4_2 == 0)//小数位是0
                            {
                                hp.PathDiff = PathDiff.ToString();
                            }
                            else
                            {
                                hp.PathDiff = (Math.Pow(10, -t4_2) * PathDiff).ToString("F" + t4_2);
                            }


                            dIndex += 4;

                            string t7 = data1.Substring(dIndex, 4);  //低限阀值 最高位是1是负数

                            int t7_i = CRC.HexToInt(t7);
                            int PathMin = 0;
                            if (t7_i < 32768)
                            {
                                PathMin = t7_i;
                            }
                            else
                            {
                                PathMin = -(65536 - t7_i);
                            }

                            if (t4_2 == 0)//小数位是0
                            {
                                hp.PathMin = PathMin.ToString();
                            }
                            else
                            {
                                hp.PathMin = (Math.Pow(10, -t4_2) * PathMin).ToString("F" + t4_2);
                            }

                            dIndex += 4;

                            string t8 = data1.Substring(dIndex, 4);  //高限阀值 最高位是1是负数
                            int t8_i = CRC.HexToInt(t8);
                            int PathMax = 0;
                            if (t8_i < 32768)
                            {
                                PathMax = t8_i;
                            }
                            else
                            {
                                PathMax = -(65536 - t8_i);
                            }
                            if (t4_2 == 0)//小数位是0
                            {
                                hp.PathMax = PathMax.ToString();
                            }
                            else
                            {
                                hp.PathMax = (Math.Pow(10, -t4_2) * PathMax).ToString("F" + t4_2);
                            }
                            dIndex += 4;

                            //string t9 = data1.Substring(dIndex, 32);  //通道名称
                            //if(t9== "00000000000000000000000000000000")
                            //{
                            //    hp.PathName = "通道名称" + (i + 1).ToString();
                            //    //更新设备名称
                            //   //ToolUtil.SetPathName(v.IP, v.Port, v.EquAD, hp.PathName, i + 1);
                            //}
                            //else
                            //{
                            //    hp.PathName = CRC.GetChsFromHex(t9);
                            //}


                            hp.IsSync = 1;
                            hp.IsSyncTime = DateTime.Now;
                            hp.Status = 1;
                            if (iu)
                            {
                                new HT_PathB().Insert(hp);
                            }
                            else
                            {
                                new HT_PathB().Update(hp);
                            }

                            pnoList += "," + hp.ID.ToString();
                        }

                        //删除无用的通道
                        new HT_PathB().ExsSql("delete from HT_PathData where LYID='"+ v.ID + "' and PID not in ("+ pnoList.Substring(1)+ ")");
                        new HT_PathB().ExsSql("delete from HT_Path where LYID='" + v.ID + "' and ID not in (" + pnoList.Substring(1) + ")");
                        #endregion

                    }
                }
                #endregion

                #region 3.获取通道数据
                var listAll1 = new HT_PathB().GetDTByCommand("select p.*,l.IP,l.Port,l.EquAD from HT_Path p join HT_Layer l on p.LYID=l.ID where p.status=1 and l.IP!='' order by p.LYID,p.PathNo");
                dIndex = 0;
                int pIdx = 0;
                string layerid = "";
                foreach (DataRow dr in listAll1.Rows)
                {
                    dIndex = 0;
                    string pathdata = ToolUtil.GetPathData(dr["IP"].ToString(), dr["Port"].ToString(), dr["EquAD"].ToString(), Int32.Parse(dr["PathNo"].ToString()) - 1);
                    pathdata = pathdata.Replace(" ", "");
                    if (pathdata != "")
                    {
                        

                        HT_PathData hpd = new HT_PathData();
                        hpd.LYID = Int32.Parse(dr["LYID"].ToString());
                        hpd.PID = Int32.Parse(dr["ID"].ToString());
                        hpd.PathNo = dr["PathNo"].ToString();
                        hpd.PathType = dr["PathType"].ToString();
                        hpd.CRTime = DateTime.Now;

                        int len2 = CRC.HexToInt(pathdata.Substring(4, 2)) * 2; //一个字节两位
                        string data2 = pathdata.Substring(6, len2);

                        string t1 = data2.Substring(dIndex, 4);  //通道编号
                        string t1_1 = t1.Substring(0, 2); //编号
                        string t1_2 = t1.Substring(2, 2);   //状态   00,01
                        int status = CRC.HexToInt(t1_2);
                        hpd.PathStatus = GetPathStatus(status);
                        dIndex += 4;


                        string t2 = data2.Substring(dIndex, 4);  //
                        int t2_1 = CRC.HexToInt(t2.Substring(0, 2)); //小数位数
                        int t2_2 = CRC.HexToInt(t2.Substring(2, 2)); //符号位
                        dIndex += 4;


                        string t3 = data2.Substring(dIndex, 4);  //高16位
                        dIndex += 4;

                        string t4 = data2.Substring(dIndex, 4);  //低16位



                        int iValue = CRC.HexToInt(t3 + t4);
                        if (t2_1 == 0)//没有小数点
                        {
                            hpd.PathValue = t2_2 == 0 ? iValue.ToString() : (-iValue).ToString();
                        }
                        else//有小数点
                        {
                            double iDecimal = Math.Pow(10, -t2_1);
                            decimal pValue = (decimal)(iValue * iDecimal);
                            hpd.PathValue = t2_2 == 0 ? pValue.ToString("n" + t2_1) : (-pValue).ToString("n" + t2_1);
                        }


                        new HT_PathDataB().Insert(hpd);

                        //告警
                        if (status == 2 || status == 3 || status == 5)
                        {
                            new HT_PathB().ExsSql("update HT_Path set Flag='1' , FlagTime=getdate(),PathStatus='" + hpd.PathStatus + "',PathData='" + hpd.PathValue + "' where ID='" + dr["ID"].ToString() + "'");
                        }
                        else
                        {
                            new HT_PathB().ExsSql("update HT_Path set Flag='',FlagTime=getdate(),PathStatus='" + hpd.PathStatus + "',PathData='" + hpd.PathValue + "' where ID='" + dr["ID"].ToString() + "'");
                        }

                    }

                    if (runCount % 3 == 0)
                    {
                        if (pathdata.Trim(' ') == "")
                        {
                            new HT_LayerB().ExsSql("update HT_Layer set Status='0' where ID=" + dr["LYID"].ToString());
                        }
                        else
                        {
                            new HT_LayerB().ExsSql("update HT_Layer set Status='1' where ID=" + dr["LYID"].ToString());
                        }

                       
                    }


                }


                #endregion


            }
            catch (Exception ex)
            {
                string ss = ex.Message;
                CommonClass.WriteLog("err", "err", ss);
            }
        }

        #endregion

        #region 类型转换
        //通道类型
        public string GetPathType(int type)
        {
            string strType = "";
            switch (type)
            {
                case 1:
                    {
                        strType = "压力";
                    }
                    break;
                case 2:
                    {
                        strType = "流量";
                    }
                    break;
                case 3:
                    {
                        strType = "氧气浓度";
                    }
                    break;
            }

            return strType;
        }


        //        0    吸引
        //1   二氧化碳
        //2   氮气
        //3   笑气
        //4   氧气
        //5   医用空气

        public string GetPathTypeName(int type)
        {
            string strType = "";
            switch (type)
            {
                case 1:
                    {
                        strType = "吸引";
                    }
                    break;
                case 2:
                    {
                        strType = "二氧化碳";
                    }
                    break;
                case 3:
                    {
                        strType = "氮气";
                    }
                    break;
                case 4:
                    {
                        strType = "笑气";
                    }
                    break;
                case 5:
                    {
                        strType = "氧气";
                    }
                    break;
                case 6:
                    {
                        strType = "医用空气";
                    }
                    break;
            }

            return strType;
        }

        //设备检测单位表
        public string GetPathUnit(int type)
        {
            string strType = "";
            switch (type)
            {
                case 1:
                    {
                        strType = "KPa";
                    }
                    break;
                case 2:
                    {
                        strType = "MPa";
                    }
                    break;
                case 3:
                    {
                        strType = "L/min";
                    }
                    break;
                case 4:
                    {
                        strType = "m3";//立方米
                    }
                    break;
                case 5:
                    {
                        strType = "%VOL";
                    }
                    break;
            }

            return strType;
        }

        //设备检测通道状态表

        public string GetPathStatus(int type)
        {
            string strType = "";
            switch (type)
            {
                case 0:
                    {
                        strType = "通道初始化";
                    }
                    break;
                case 1:
                    {
                        strType = "正常";
                    }
                    break;
                case 2:
                    {
                        strType = "低报";
                    }
                    break;
                case 3:
                    {
                        strType = "高报";
                    }
                    break;
                case 5:
                    {
                        strType = "通道故障";
                    }
                    break;

            }

            return strType;
        }

        #endregion

        #region 备份,日志管理
        public void GETDATACOUNT(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            //1.通道数据量
            string sql = "select count(1) as qty from HT_PathData";
            msg.result = new HT_PathDataB().ExsSclarSql(sql).ToString();
        }

        public void GETLOG(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            string strWhere = " 1=1 ";
            if (P1 != "")
            {
                strWhere += " and l.Type='" + P1 + "'";
            }
            //if (P2 != "")
            //{
            //    strWhere += " and l.ID='" + P2 + "'";
            //}
            int total = 0;

            var dt = new HT_PathDataB().GetDataPager("HT_Log l left join HT_Auth_User u on l.CRUser=u.ID", "l.*,u.UserName", page.pagecount, page.pageindex, " l.CRTime desc", strWhere, ref total);

            msg.result = dt;
            msg.total = total;
        }
        public void BKDATA(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            if (P1 != "")
            {
                string SQL1 = "SELECT count(1) as qty from HT_PathData where CRTime<='" + P1 + "' ";
                int qty = Int32.Parse(new HT_PathDataB().ExsSclarSql(SQL1));

                string SQL = " insert into HT_PathData_bak SELECT PID,PathNo,PathType,PathStatus,PathValue,CRTime,LYID from HT_PathData where CRTime<='" + P1 + "' ";
                SQL += " DELETE from HT_PathData where CRTime<='" + P1 + "' ";

                new HT_PathDataB().ExsSql(SQL);

                new HT_LogB().Insert(new HT_Log()
                {
                    CRUser = authuser != null ? authuser.ID : 0,
                    CRTime = DateTime.Now,
                    CRContent = "备份",
                    Type = "bk",
                    BKTime = DateTime.Parse(P1),
                    BKCount = qty
                });

                new HT_ConfigB().ExsSql("update HT_Config set BackupTimeLast=GETDATE() where ID=1");
            }
        }
        public void BKDATA2(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            if (P1 != "")
            {
                string SQL = " DELETE from HT_PathData_bak where CRTime<='" + P1 + "' ";
                new HT_PathDataB().ExsSql(SQL);

                new HT_ConfigB().ExsSql("update HT_Config set ClearTimeLast=GETDATE() where ID=1");
            }


        }

        #endregion

        #region 报警
        /// <summary>
        /// 报警
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void GETERROR(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var dt = new HT_ConfigB().GetDTByCommand("select top 1 * from HT_Config ");
            if (dt.Rows.Count > 0 && dt.Rows[0]["CallFlag"].ToString() == "1")
            {
                string SQL = " select top 10 l.EquName,h.PathName,h.PathType,h.PathStatus,convert(char(10),h.FlagTime,108) as FlagTime,h.PathData from HT_Path h join HT_Layer l on h.LYID=l.ID where Flag = '1' ORDER BY h.FlagTime DESC ";

                msg.result = new HT_PathDataB().GetDTByCommand(SQL);
            }

        }
        #endregion
        #region 统计
        /// <summary>
        /// 设备情况
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="page"></param>
        /// <param name="authuser"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        public void GETLAYERTS(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            //var dt = new HT_ConfigB().GetDTByCommand("select top 1 * from HT_Config ");
            //if (dt.Rows.Count > 0 && dt.Rows[0]["CallFlag"].ToString() == "1")
            //{
                string SQL = "SELECT l.*,h.LouNo,AA.Flag,isnull(AA.FlagTime,getdate()) as FlagTime,isnull(AA.PathName,'无') as PathName,isnull(AA.PathStatus,'正常') as PathStatus FROM HT_Layer l join HT_Lou h on l.LouID=h.ID OUTER apply (select top 1 d.* from HT_Path d WHERE l.ID = d.LYID AND d.Flag = '1' ORDER BY d.CRTime desc)AA where l.IP!='' and l.Port!='' and l.EquAD!='' ORDER BY l.LouID,l.LYNO ";
                msg.result = new HT_PathB().GetDTByCommand(SQL);
            //}
        }
        public void GETCONFIG(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            msg.result = new HT_ConfigB().GetEntity(p => p.ID == 1);
        }
        public void SETCONFIG(HttpContext context, Msg_Result msg, Msg_Page page, HT_Auth_User authuser, string P1, string P2)
        {
            var tt = JsonConvert.DeserializeObject<HT_Config>(P1);

            new HT_ConfigB().Update(tt);
        }

        #endregion
    }






}

